package com.leetcode.q24;

/**
 * <p> description: 链表相邻节点位置交换
 * 可优化，使用递归，让算法思路更清晰
 * </p>
 *
 * @author tanzc
 * @date 2022/3/31
 **/
public class SwapPairs {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        head = swapPair(head);
        ListNode p = head.next.next, q = head.next;
        while (p != null) {
            p = swapPair(p);
            q.next = p;
            if (p == null || p.next == null) {
                break;
            }
            p = p.next.next;
            q = q.next.next;
        }
        return head;
    }

    public ListNode swapPair(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = head, q = head.next;
        p.next = q.next;
        q.next = p;
        p = q;
        return p;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
